/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    stm32f1xx_it.c
  * @brief   Interrupt Service Routines.
  ******************************************************************************
  * @attention
  *
  * <h2><center>&copy; Copyright (c) 2021 STMicroelectronics.
  * All rights reserved.</center></h2>
  *
  * This software component is licensed by ST under BSD 3-Clause license,
  * the "License"; You may not use this file except in compliance with the
  * License. You may obtain a copy of the License at:
  *                        opensource.org/licenses/BSD-3-Clause
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "stm32f1xx_it.h"
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "stdlib.h"
#include "string.h"
#include "axis.h"
#include "queue.h"
#include "sio_service.h"
#include "motion_service.h"
#include "mcu_application.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN TD */

/* USER CODE END TD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/
/* USER CODE BEGIN PV */
extern char message_LED0_ON[];
extern char message_LED0_OFF[];
extern char signal;

extern TiAxis *axis_X;
extern TiAxis *axis_Y;
extern TiAxis *axis_Z;
extern uint8_t* request;
extern uint8_t* response;
extern TiSioService *sio;
extern TiMotionService *mcs;
extern Queue *task_seq;
extern TiMcuApplication *mcu_app;
/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
/* USER CODE BEGIN PFP */

/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

/* USER CODE END 0 */

/* External variables --------------------------------------------------------*/
extern TIM_HandleTypeDef htim2;
extern TIM_HandleTypeDef htim3;
extern TIM_HandleTypeDef htim4;
extern DMA_HandleTypeDef hdma_usart1_rx;
extern DMA_HandleTypeDef hdma_usart2_tx;
extern DMA_HandleTypeDef hdma_usart2_rx;
extern UART_HandleTypeDef huart1;
extern UART_HandleTypeDef huart2;
/* USER CODE BEGIN EV */

/* USER CODE END EV */

/******************************************************************************/
/*           Cortex-M3 Processor Interruption and Exception Handlers          */ 
/******************************************************************************/
/**
  * @brief This function handles Non maskable interrupt.
  */
void NMI_Handler(void)
{
  /* USER CODE BEGIN NonMaskableInt_IRQn 0 */

  /* USER CODE END NonMaskableInt_IRQn 0 */
  /* USER CODE BEGIN NonMaskableInt_IRQn 1 */

  /* USER CODE END NonMaskableInt_IRQn 1 */
}

/**
  * @brief This function handles Hard fault interrupt.
  */
void HardFault_Handler(void)
{
  /* USER CODE BEGIN HardFault_IRQn 0 */

  /* USER CODE END HardFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_HardFault_IRQn 0 */
    /* USER CODE END W1_HardFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Memory management fault.
  */
void MemManage_Handler(void)
{
  /* USER CODE BEGIN MemoryManagement_IRQn 0 */

  /* USER CODE END MemoryManagement_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_MemoryManagement_IRQn 0 */
    /* USER CODE END W1_MemoryManagement_IRQn 0 */
  }
}

/**
  * @brief This function handles Prefetch fault, memory access fault.
  */
void BusFault_Handler(void)
{
  /* USER CODE BEGIN BusFault_IRQn 0 */

  /* USER CODE END BusFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_BusFault_IRQn 0 */
    /* USER CODE END W1_BusFault_IRQn 0 */
  }
}

/**
  * @brief This function handles Undefined instruction or illegal state.
  */
void UsageFault_Handler(void)
{
  /* USER CODE BEGIN UsageFault_IRQn 0 */

  /* USER CODE END UsageFault_IRQn 0 */
  while (1)
  {
    /* USER CODE BEGIN W1_UsageFault_IRQn 0 */
    /* USER CODE END W1_UsageFault_IRQn 0 */
  }
}

/**
  * @brief This function handles System service call via SWI instruction.
  */
void SVC_Handler(void)
{
  /* USER CODE BEGIN SVCall_IRQn 0 */

  /* USER CODE END SVCall_IRQn 0 */
  /* USER CODE BEGIN SVCall_IRQn 1 */

  /* USER CODE END SVCall_IRQn 1 */
}

/**
  * @brief This function handles Debug monitor.
  */
void DebugMon_Handler(void)
{
  /* USER CODE BEGIN DebugMonitor_IRQn 0 */

  /* USER CODE END DebugMonitor_IRQn 0 */
  /* USER CODE BEGIN DebugMonitor_IRQn 1 */

  /* USER CODE END DebugMonitor_IRQn 1 */
}

/**
  * @brief This function handles Pendable request for system service.
  */
void PendSV_Handler(void)
{
  /* USER CODE BEGIN PendSV_IRQn 0 */

  /* USER CODE END PendSV_IRQn 0 */
  /* USER CODE BEGIN PendSV_IRQn 1 */

  /* USER CODE END PendSV_IRQn 1 */
}

/**
  * @brief This function handles System tick timer.
  */
void SysTick_Handler(void)
{
  /* USER CODE BEGIN SysTick_IRQn 0 */

  /* USER CODE END SysTick_IRQn 0 */
  HAL_IncTick();
  /* USER CODE BEGIN SysTick_IRQn 1 */

  /* USER CODE END SysTick_IRQn 1 */
}

/******************************************************************************/
/* STM32F1xx Peripheral Interrupt Handlers                                    */
/* Add here the Interrupt Handlers for the used peripherals.                  */
/* For the available peripheral interrupt handler names,                      */
/* please refer to the startup file (startup_stm32f1xx.s).                    */
/******************************************************************************/

/**
  * @brief This function handles DMA1 channel5 global interrupt.
  */
void DMA1_Channel5_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel5_IRQn 0 */

  /* USER CODE END DMA1_Channel5_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart1_rx);
  /* USER CODE BEGIN DMA1_Channel5_IRQn 1 */

  /* USER CODE END DMA1_Channel5_IRQn 1 */
}

/**
  * @brief This function handles DMA1 channel6 global interrupt.
  */
void DMA1_Channel6_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel6_IRQn 0 */

  /* USER CODE END DMA1_Channel6_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart2_rx);
  /* USER CODE BEGIN DMA1_Channel6_IRQn 1 */

  /* USER CODE END DMA1_Channel6_IRQn 1 */
}

/**
  * @brief This function handles DMA1 channel7 global interrupt.
  */
void DMA1_Channel7_IRQHandler(void)
{
  /* USER CODE BEGIN DMA1_Channel7_IRQn 0 */

  /* USER CODE END DMA1_Channel7_IRQn 0 */
  HAL_DMA_IRQHandler(&hdma_usart2_tx);
  /* USER CODE BEGIN DMA1_Channel7_IRQn 1 */

  /* USER CODE END DMA1_Channel7_IRQn 1 */
}

/**
  * @brief This function handles EXTI line[9:5] interrupts.
  */
void EXTI9_5_IRQHandler(void)
{
  /* USER CODE BEGIN EXTI9_5_IRQn 0 */

  /* USER CODE END EXTI9_5_IRQn 0 */
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_8);
  HAL_GPIO_EXTI_IRQHandler(GPIO_PIN_9);
  /* USER CODE BEGIN EXTI9_5_IRQn 1 */

  /* USER CODE END EXTI9_5_IRQn 1 */
}

/**
  * @brief This function handles TIM2 global interrupt.
  */
void TIM2_IRQHandler(void)
{
  /* USER CODE BEGIN TIM2_IRQn 0 */

  /* USER CODE END TIM2_IRQn 0 */
  HAL_TIM_IRQHandler(&htim2);
  /* USER CODE BEGIN TIM2_IRQn 1 */

  /* USER CODE END TIM2_IRQn 1 */
}

/**
  * @brief This function handles TIM3 global interrupt.
  */
void TIM3_IRQHandler(void)
{
  /* USER CODE BEGIN TIM3_IRQn 0 */

  /* USER CODE END TIM3_IRQn 0 */
  HAL_TIM_IRQHandler(&htim3);
  /* USER CODE BEGIN TIM3_IRQn 1 */

  /* USER CODE END TIM3_IRQn 1 */
}

/**
  * @brief This function handles TIM4 global interrupt.
  */
void TIM4_IRQHandler(void)
{
  /* USER CODE BEGIN TIM4_IRQn 0 */

  /* USER CODE END TIM4_IRQn 0 */
  HAL_TIM_IRQHandler(&htim4);
  /* USER CODE BEGIN TIM4_IRQn 1 */

  /* USER CODE END TIM4_IRQn 1 */
}

/**
  * @brief This function handles USART1 global interrupt.
  */
void USART1_IRQHandler(void)
{
  /* USER CODE BEGIN USART1_IRQn 0 */

  /* USER CODE END USART1_IRQn 0 */
  HAL_UART_IRQHandler(&huart1);
  /* USER CODE BEGIN USART1_IRQn 1 */
  USER_UART_IDLE_IRQHandler(&huart1);
#ifdef DEBUG_MODE
  USER_Receive_task();
#endif
  /* USER CODE END USART1_IRQn 1 */
}

/**
  * @brief This function handles USART2 global interrupt.
  */
void USART2_IRQHandler(void)
{
  /* USER CODE BEGIN USART2_IRQn 0 */

  /* USER CODE END USART2_IRQn 0 */
  HAL_UART_IRQHandler(&huart2);
  /* USER CODE BEGIN USART2_IRQn 1 */
  USER_UART_IDLE_IRQHandler(&huart2);
  USER_Receive_task();
  /* USER CODE END USART2_IRQn 1 */
}

/* USER CODE BEGIN 1 */
/**
  * @brief  UART IDLE IRQHandler.
  *
  * @note   This function executes operations when a IDLE interrupt rises. In this project, we move received bytes
  * 		to the receive queue of serial input&output service for further extraction.
  *
  * @param  huart	A UART handler.
  * @retval None.
  */
void USER_UART_IDLE_IRQHandler(UART_HandleTypeDef *huart)
{
	if (USART2 == huart->Instance)
	{
		if (__HAL_UART_GET_FLAG(&huart2, UART_FLAG_IDLE)!=RESET)
		  {
			  __HAL_UART_CLEAR_IDLEFLAG(&huart2);
			  HAL_UART_DMAStop(&huart2);
			  USART2_RX.len = BUF_MAX_LENGTH - __HAL_DMA_GET_COUNTER(&hdma_usart2_rx);
			  *(USART2_RX.p_data+USART2_RX.len) = '\0';
			  sio->rxlen = USART2_RX.len;
			  memcpy(sio->rxque, USART2_RX.p_data, sio->rxlen);
			  //printf("%s\n",USART2_RX.p_data);
			  while (HAL_UART_Receive_DMA(&huart2, (uint8_t*)USART2_RX.p_data, BUF_MAX_LENGTH)!=HAL_OK);
		  }
	}
	else if (USART1 == huart->Instance)
  	{
  		if (__HAL_UART_GET_FLAG(&huart1, UART_FLAG_IDLE)!=RESET)
  		  {
  			  __HAL_UART_CLEAR_IDLEFLAG(&huart1);
  			  HAL_UART_DMAStop(&huart1);
  			  USART1_RX.len = BUF_MAX_LENGTH - __HAL_DMA_GET_COUNTER(&hdma_usart1_rx);
  			  *(USART1_RX.p_data+USART1_RX.len) = '\0';
#ifndef DEBUG_MODE
			printf("%s checked\n",USART1_RX.p_data);
#endif
  			  while (HAL_UART_Receive_DMA(&huart1, (uint8_t*)USART1_RX.p_data, BUF_MAX_LENGTH)!=HAL_OK);
  		  }
  	}
}

/**
  * @brief  TIMER period elapsed callback function.
  *
  * @note   This function counts pulses a PWM channel has output according to the direction.
  * 		Note that it can indirectly present the angle an axis has rotated.
  *
  * @param  htim	A TIMER handler.
  * @retval None.
  */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (htim->Instance == TIM2)
	{
		__HAL_TIM_CLEAR_FLAG(htim,TIM_IT_UPDATE);
		if (axis_X->motor->direction == 'P')
			axis_X->encoder += 1;
		else if (axis_X->motor->direction == 'N')
			axis_X->encoder -= 1;
	}
	if (htim->Instance == TIM3)
	{
		__HAL_TIM_CLEAR_FLAG(htim,TIM_IT_UPDATE);
		if (axis_Y->motor->direction == 'P')
			axis_Y->encoder += 1;
		else if (axis_Y->motor->direction == 'N')
			axis_Y->encoder -= 1;
	}
	if (htim->Instance == TIM4)
	{
		__HAL_TIM_CLEAR_FLAG(htim,TIM_IT_UPDATE);
		if (axis_Z->motor->direction == 'P')
			axis_Z->encoder += 1;
		else if (axis_Z->motor->direction == 'N')
			axis_Z->encoder -= 1;
	}
}

/**
  * @brief  GPIO external interrupt callback function.
  *
  * @note   This function provides a measure to check an axis returning to zero or not.
  *
  * @param  GPIO_Pin	GPIO pin the zero adjuster mapping to.
  * @retval None.
  */
void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{
	//HAL_Delay(50);
	switch (GPIO_Pin)
	{
	case MOTOR_Y_ZERO_Pin:
		if (HAL_GPIO_ReadPin(MOTOR_Y_ZERO_GPIO_Port,MOTOR_Y_ZERO_Pin) == GPIO_PIN_RESET)
		{
			axis_Y->zero_flag = 1;
		}
		else if (HAL_GPIO_ReadPin(MOTOR_Y_ZERO_GPIO_Port,MOTOR_Y_ZERO_Pin) == GPIO_PIN_SET)
		{
			axis_Y->zero_flag = 0;
		}
		break;
	case MOTOR_Z_ZERO_Pin:
		if (HAL_GPIO_ReadPin(MOTOR_Z_ZERO_GPIO_Port,MOTOR_Z_ZERO_Pin) == GPIO_PIN_RESET)
		{
			axis_Z->zero_flag = 1;
		}
		else if (HAL_GPIO_ReadPin(MOTOR_Z_ZERO_GPIO_Port,MOTOR_Z_ZERO_Pin) == GPIO_PIN_SET)
		{
			axis_Z->zero_flag = 0;
		}
		break;
	default:
		break;
	}
	__HAL_GPIO_EXTI_CLEAR_IT(GPIO_Pin);
}

/**
  * @brief  Extra instruction and interpret it.
  *
  * @note   This function provided extras instruction from receive buffer of serial input&output service
  * 		and interpret it into different type, and then makes response(push to task queue or send information).
  *
  * @retval None.
  */
void USER_Receive_task(void)
{
#ifndef DEBUG_MODE
	if (sio_recv(sio) != SIOSERVICE_ERROR)
	{
		//sio_trans(sio,(uint8_t*)"ACK");
		strcpy((char*)request,(char*)sio->rxbuf);
		memset(sio->rxbuf,0x00,127);
#endif
#ifdef DEBUG_MODE
		memcpy(request, USART1_RX.p_data, USART1_RX.len);
		memset(USART1_RX.p_data,0x00,BUF_MAX_LENGTH);
		USART1_RX.len = 0;
#endif
		uint8_t type;
		TiTask task;
		if (mcs_interpret(request,strlen((char*)request),response,&type) == MOTIONSERVICE_OK)
		{
			switch (type)
			{
			case MOV_ROTATE:
				task.type = MOV_ROTATE;
				sscanf((char*)response, "[%f],[%f],[%f],[%f],[%f],[%f]",
						&task.value[0], &task.value[1], &task.value[2], &task.value[3], &task.value[4], &task.value[5]);
				QueuePush(task_seq,task);
				break;
			case MOV_ZERO:
				task.type = MOV_ZERO;
				QueuePush(task_seq,task);
				break;
			case MOV_STOP:
				task.type = MOV_STOP;
				QueueInsertFront(task_seq,task);
				break;
			case MOV_START:
				task.type = MOV_START;
				QueuePush(task_seq,task);
				break;
			case GET_ANGLE:
			{
				uint8_t* angle_info=(uint8_t*) malloc(127);
				uint8_t* back_info=(uint8_t*) malloc(BUF_MAX_LENGTH);
				sprintf((char*)angle_info,"AngleValue:[%.3f][%.3f][%.3f]",
					  (float)(axis_read(axis_X)*STEP_ANGLE),
					  (float)(axis_read(axis_Y)*STEP_ANGLE),
					  (float)(axis_read(axis_Z)*STEP_ANGLE));
				sprintf((char*)back_info,"%c%c%c%c%c%s%c%c",0xff,0xff,0x01,0x01,
					  (uint8_t)(strlen((char*)angle_info) + 2),(char*)angle_info,0x0d,0x0a);
				sio_trans(sio,back_info);
				break;
			}
			//maybe ambiguous
			case OBJ_CLOSE:
				task.type = OBJ_CLOSE;
				QueuePush(task_seq, task);
				break;
			case OBJ_OPEN:
				task.type = OBJ_OPEN;
				QueuePush(task_seq, task);
				break;
			default:
				break;
			}
			memset(response,0x00,127);
		}
#ifndef DEBUG_MODE
		else
		{
			sio_trans(sio,(uint8_t*)"NACK");
		}
	}
#endif
}
/* USER CODE END 1 */
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
